package com.apache.client.protocol;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Map;

import com.apache.api.vo.ResultEntity;
import com.apache.attachment.mommon.ToolsUtil;
import com.apache.attachment.mommon.XmlUtil;

/**
 * description:  socket通信接口实现
 * @author dwu 创建时间：2015-10-15  
 * @Copyright(c)2015:北京--软件技术有限公司
 */
public class SocketProtocolService extends AbstractProtocolClient {

	public ResultEntity doService(String beanId, String methodKey, Map<String, Object> params) {
		ResultEntity resultEntity = null;
		Socket server = null;
		String httpIp = ToolsUtil.getInstance().getValueByKey("attaServer_ip");
		String httpPort = ToolsUtil.getInstance().getValueByKey("attaServer_port");
		//System.out.println("httpIp=" + httpIp + "---httpPort=" + httpPort);
		if (ToolsUtil.isNull(httpPort))
			httpPort = "9001";
		try {
			String xmlParams = this.buildXml(beanId, methodKey, "XML", params);
			server = new Socket();
			SocketAddress remoteAddr = new InetSocketAddress(httpIp, Integer.parseInt(httpPort));
			server.connect(remoteAddr, 30000); //等待建立连接的超时时间为30秒
			server.setSoTimeout(Integer.parseInt(ToolsUtil.isNull(ToolsUtil.getInstance()
					.getValueByKey("socketTimeOut"), "100")));//毫秒
			String temp = doSocket(server, xmlParams);
			if (ToolsUtil.isNull(temp)) {
				resultEntity = getResultEntity("接口调用超时");
				return resultEntity;
			}
			resultEntity = XmlUtil.toBean(temp, ResultEntity.class);
		} catch (Exception e1) {
			resultEntity = getResultEntity(e1.getMessage());
		} finally {
			try {
				if (null != server)
					server.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultEntity;
	}

	private String doSocket(Socket socket, String params) throws IOException {
		String temp = "";
		socket.getOutputStream().write(params.getBytes("UTF-8"));
		socket.getOutputStream().flush();
		StringBuffer rtnMsgc = new StringBuffer();

		byte[] bs_Length = new byte[4];
		int readLength = socket.getInputStream().read(bs_Length, 0, 4);
		int dataLength = 0;
		if (readLength > 0) {
			dataLength = bytesToInt(bs_Length);
		}
		if (dataLength < 1) {
			return temp;
		}

		BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
		String str;
		while ((str = rd.readLine()) != null) {
			rtnMsgc.append(str + "\n");
		}
		temp = rtnMsgc.toString();
		return temp;
	}

	private int bytesToInt(byte[] bytes) {
		int number = bytes[0] & 0xFF;

		number |= bytes[1] << 8 & 0xFF00;
		number |= bytes[2] << 16 & 0xFF0000;
		number |= bytes[3] << 24 & 0xFF000000;
		return number;
	}

}
